package com.codeest.geeknews;

import java.util.concurrent.Callable;

import io.reactivex.Scheduler;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.TestScheduler;

/**
 * Created by admin on 2017/7/7.
 */

public class RxUnitTestTools {
    private static boolean isInitRxTools = false;

    /**
     * 把异步变成同步，方便测试
     */
    public static void openRxTools() {
        if (isInitRxTools) {
            return;
        }
        isInitRxTools = true;


//        RxAndroidSchedulersHook rxAndroidSchedulersHook = new RxAndroidSchedulersHook() {
//            @Override
//            public Scheduler getMainThreadScheduler() {
//                return Schedulers.immediate();
//            }
//        };
//
//        RxJavaSchedulersHook rxJavaSchedulersHook = new RxJavaSchedulersHook() {
//            @Override
//            public Scheduler getIOScheduler() {
//                return Schedulers.immediate();
//            }
//        };
//
//        // reset()不是必要，实践中发现不写reset()，偶尔会出错，所以写上保险^_^
//        RxAndroidPlugins.reset();
//        RxAndroidPlugins.registerSchedulersHook(rxAndroidSchedulersHook);
//        RxJavaPlugins.reset();
//        RxJavaPlugins.registerSchedulersHook(rxJavaSchedulersHook);


        RxAndroidPlugins.reset();
        RxAndroidPlugins.setInitMainThreadSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() {
            @Override
            public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception {
                return new TestScheduler();
            }
        });
        RxJavaPlugins.reset();
        RxJavaPlugins.setInitIoSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() {
            @Override
            public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception {
                return new TestScheduler();
            }
        });
    }
}
